import { UploadItem } from '@arco-design/web-react/es/Upload';
import { ApiValues, FormValues } from './constant';

function getUploadItemUrl(uploadItems: UploadItem[]): string {
  return (
    uploadItems?.[0]?.url || (uploadItems?.[0]?.response as any)?.data || ''
  );
}

export function convertFormValueToApiParam(form: FormValues): ApiValues {
  let bankCity;
  try {
    if (form.bankCity) {
      bankCity = JSON.stringify(form.bankCity);
    }
  } catch (error) {}
  const api: ApiValues = {
    ...form,
    managerWxCode: getUploadItemUrl(form.managerWxCode),
    tradeMarkAuthorization: getUploadItemUrl(form.tradeMarkAuthorization),
    legalPersonIdCardFront: getUploadItemUrl(form.legalPersonIdCardFront),
    legalPersonIdCardBack: getUploadItemUrl(form.legalPersonIdCardBack),
    businessLicense: getUploadItemUrl(form.businessLicense),
    bankLicense: getUploadItemUrl(form.bankLicense),
    legalPersonIdCardNotExpire: form.legalPersonIdCardNotExpire ? 1 : 0,
    bankCity: bankCity || ''
  };
  return api;
}

function getUploadItem(uploadUrl?: string): UploadItem[] {
  if (!uploadUrl) {
    return [];
  }
  return [
    {
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: uploadUrl
    }
  ];
}

export function convertApiRespToFormValue(api: ApiValues): FormValues {
  let bankCity;
  try {
    if (api.bankCity) {
      bankCity = JSON.parse(api.bankCity);
    }
  } catch (error) {}
  const form: FormValues = {
    ...api,
    managerWxCode: getUploadItem(api.managerWxCode),
    tradeMarkAuthorization: getUploadItem(api.tradeMarkAuthorization),
    legalPersonIdCardFront: getUploadItem(api.legalPersonIdCardFront),
    legalPersonIdCardBack: getUploadItem(api.legalPersonIdCardBack),
    businessLicense: getUploadItem(api.businessLicense),
    bankLicense: getUploadItem(api.bankLicense),
    legalPersonIdCardNotExpire: Boolean(api.legalPersonIdCardNotExpire),
    bankCity: bankCity ?? {}
  };
  return form;
}

export function validateLegalPersonIdCardExpireTime(form, callback) {
  const legalPersonIdCardExpireTimeStr = form.getFieldValue(
    'legalPersonIdCardExpireTimeStr'
  );
  const legalPersonIdCardNotExpire = form.getFieldValue(
    'legalPersonIdCardNotExpire'
  );

  if (!legalPersonIdCardExpireTimeStr && !legalPersonIdCardNotExpire) {
    callback('请选择身份证有效截止日期');
  } else {
    callback();
  }
}
